<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:student:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" width="50" align="center" prop="studentId" />
      <el-table-column label="学号" align="center" prop="studentNo" />
      <el-table-column label="姓名" width="80" align="center" prop="studentName" />
      <el-table-column label="性别" width="60" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="家长名称"  width="80" align="center" prop="parentName" />
      <el-table-column label="关系" width="80" align="center" prop="parentType" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="年级信息" align="center" prop="gradeId" :formatter="(row) => formaterGradeName(row.gradeId)" />
      <el-table-column label="班级信息" align="center" prop="classId" :formatter="(row) => formaterClassName(row.classId)" />
      <el-table-column label="自习室" align="center" prop="classroomId" :formatter="(row) => formaterClassroomName(row.classroomId)" />
      <el-table-column label="自习坐标" align="center" prop="seatId" :formatter="(row) => formaterSeatName(row.seatId)" />
      <el-table-column label="寝室" align="center" prop="dormId" :formatter="(row) => formaterDormName(row.dormId)" />
      <el-table-column label="床位坐标" align="center" prop="bedId" :formatter="(row) => formaterBedName(row.bedId)" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:student:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:student:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-divider>基本信息</el-divider>
          <el-col :span="12">
            <el-form-item label="姓名" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="form.studentNo" placeholder="请输入学号(如未知可自行编号)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeId">
              <el-select v-model="form.gradeId" placeholder="请选择" @change="gradeChanges">
                <el-option v-for="grade in grades" :key="grade.gradeId" :label="grade.gradeName" :value="grade.gradeId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select v-model="form.classId" placeholder="请选择">
                <el-option v-for="classItem in classesSel" :key="classItem.classId" :label="classItem.className" :value="classItem.classId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="照片" prop="avatar">
              <image-upload v-model="form.avatar"/>
            </el-form-item>
          </el-col>
          <el-divider>自习信息</el-divider>
          <el-col :span="12">
            <el-form-item label="教室" prop="classroomId">
              <el-select v-model="form.classroomId" placeholder="请选择" @change="classroomChanges">
                <el-option v-for="classroom in classroomsSel" :key="classroom.classroomId" :label="classroom.classroomName" :value="classroom.classroomId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="座位" prop="seatId">
              <el-select v-model="form.seatId" placeholder="请选择">
                <el-option v-for="seat in seatsSel" :key="seat.seatId" :label="seat.seatName" :value="Number(seat.seatId)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider>住宿信息</el-divider>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId">
              <el-select v-model="form.floorId" placeholder="请选择" @change="floorsChanges">
                <el-option v-for="floor in floors" :key="floor.floorId" :label="floor.floorName" :value="floor.floorId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="寝室" prop="dormId">
              <el-select v-model="form.dormId" placeholder="请选择" @change="dormsChanges">
                <el-option v-for="dorm in dormsSel" :key="dorm.dormId" :label="dorm.dormName" :value="Number(dorm.dormId)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="18">
            <el-form-item label="床位" prop="bedId">
              <el-select v-model="form.bedId" placeholder="请选择">
                <el-option v-for="bed in bedsSel" :key="Number(bed.bedId)" :label="bed.bedName" :value="Number(bed.bedId)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider>其它信息</el-divider>
          <el-col :span="12">
            <el-form-item label="联系人" prop="parentName">
              <el-input v-model="form.parentName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系" prop="parentType">
              <el-input v-model="form.parentType" placeholder="请输入关系" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Student">
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/system/student";
import {listGrade} from "@/api/system/grade.js";
import {listClass} from "@/api/system/class.js";
import {listClassroom} from "@/api/system/classroom.js";
import {listSeat} from "@/api/system/seat.js";
import {listDorm} from "@/api/system/dorm.js";
import {listBed} from "@/api/system/bed.js";
import {listFloor} from "@/api/system/floor.js";

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict('sys_user_sex');

const studentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const grades = ref([]);
const classes = ref([]);
const classrooms = ref([]);
const seats = ref([]);

const floors = ref([]);
const dorms = ref([]);
const beds = ref([]);

const classesSel = ref([]);
const classroomsSel = ref([]);
const seatsSel = ref([]);

const dormsSel = ref([]);
const bedsSel = ref([]);

const isEdit = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentNo: null,
    studentName: null,
    sex: null,
    gradeId: null,
    classId: null,
    classroomId: null,
    seatLocation: null,
    dormId: null,
    bedLocation: null,
  },
  rules: {
    studentNo: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    studentName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    sex: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    gradeId: [
      { required: true, message: "年级信息不能为空", trigger: "change" }
    ],
    classId: [
      { required: true, message: "班级信息不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.pageSize = 1000
  listGrade(queryParams.value).then(response => {
    grades.value = response.rows;
  });
  listClass(queryParams.value).then(response => {
    classes.value = response.rows;
  });
  listClassroom(queryParams.value).then(response => {
    classrooms.value = response.rows;
  });
  listSeat(queryParams.value).then(response => {
    seats.value = response.rows;
  });
  listFloor(queryParams.value).then(response => {
    floors.value = response.rows;
  });
  listDorm(queryParams.value).then(response => {
    dorms.value = response.rows;
  });
  listBed(queryParams.value).then(response => {
    beds.value = response.rows;
  });
  queryParams.value.pageSize = 10
  listStudent(queryParams.value).then(response => {
    studentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function gradeChanges() {
  const selectedGradeId = form.value.gradeId;
  // 清空旧数据
  classesSel.value = [];
  classroomsSel.value = [];
  // 当存在有效年级ID时执行筛选
  if (selectedGradeId) {
    // 筛选班级数据
    classesSel.value = classes.value.filter(
        item => item.gradeId === selectedGradeId
    );
    // 筛选教室数据
    classroomsSel.value = classrooms.value.filter(
        item => item.gradeId === selectedGradeId
    );
  }
  // 清空已选的班级和教室（避免残留无效数据）
  if (!isEdit.value) {
    form.value.classId = null;
    form.value.classroomId = null;
  }
}

function classroomChanges() {
  const selectedClassroomId = form.value.classroomId;
  seatsSel.value = [];
  if (selectedClassroomId) {
    seatsSel.value = seats.value.filter(
        item => item.classroomId === selectedClassroomId
    );
  }
  if (!isEdit.value) {
    form.value.seatId = null;
  }
}

function floorsChanges() {
  const selectedFloorId = form.value.floorId;
  dormsSel.value = [];
  if (selectedFloorId) {
    dormsSel.value = dorms.value.filter(
        item => item.floorId === selectedFloorId
    );
  }
  if (!isEdit.value) {
    form.value.dormId = null;
  }
}

function dormsChanges() {
  const selectedDormId = form.value.dormId;
  bedsSel.value = [];
  if (selectedDormId) {
    bedsSel.value = beds.value.filter(
        item => item.dormId === selectedDormId
    );
  }
  if (!isEdit.value) {
    form.value.bedId = null;
  }
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    studentId: null,
    studentNo: null,
    studentName: null,
    avatar: null,
    sex: null,
    parentName: null,
    parentType: null,
    phonenumber: null,
    gradeId: null,
    classId: null,
    classroomId: null,
    seatLocation: null,
    floorId: null,
    dormId: null,
    bedLocation: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("studentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.studentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isEdit.value = true;
  const _studentId = row.studentId || ids.value
  getStudent(_studentId).then(response => {
    form.value = response.data;
    /** 刷新筛选框信息 */
    gradeChanges();
    classroomChanges();

    /** 反向确认楼层信息 */
    form.value.floorId = dorms.value.filter(item => item.dormId === Number(form.value.dormId))[0].floorId
    floorsChanges();
    dormsChanges();

    open.value = true;
    title.value = "修改学生信息";
    isEdit.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentRef"].validate(valid => {
    if (valid) {
      if (form.value.studentId != null) {
        updateStudent(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStudent(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _studentIds = row.studentId || ids.value;
  proxy.$modal.confirm('是否确认删除学生信息编号为"' + _studentIds + '"的数据项？').then(function() {
    return delStudent(_studentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/student/export', {
    ...queryParams.value
  }, `student_${new Date().getTime()}.xlsx`)
}

function formaterGradeName(id) {
  const target = grades.value.find(item => item.gradeId === id)
  return target ? `${target.gradeName}` : '数据异常'
}

function formaterClassName(id) {
  const target = classes.value.find(item => item.classId === id)
  return target ? `${target.className}` : '数据异常'
}

function formaterClassroomName(id) {
  const target = classrooms.value.find(item => item.classroomId === id)
  return target ? `${target.classroomName}` : '数据异常'
}

function formaterSeatName(id) {
  const numId = Number(id);
  const target = seats.value.find(item => item.seatId === numId)
  return target ? `${target.seatName}` : '数据异常'
}

function formaterDormName(id) {
  const target = dorms.value.find(item => item.dormId === id)
  return target ? `${target.dormName}` : '数据异常'
}

function formaterBedName(id) {
  const numId = Number(id);
  const target = beds.value.find(item => item.bedId === numId)
  return target ? `${target.bedName}` : '数据异常'
}

getList();
</script>
